package com.woniu.staff.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.exception.RebornException;
import com.woniu.exception.account.AccountException;
import com.woniu.exception.account.AccountExceptionCode;
import com.woniu.exception.permissions.PermissionsException;
import com.woniu.exception.staff.StaffException;
import com.woniu.exception.staff.StaffExceptionCode;
import com.woniu.model.Result;
import com.woniu.staff.client.PermissionsClient;
import com.woniu.staff.client.StationClient;
import com.woniu.staff.client.dto.AddAccountRoleDto;
import com.woniu.staff.client.dto.StationDto;
import com.woniu.staff.cliententity.dto.AccountDto;
import com.woniu.staff.cliententity.form.AccountLoginForm;
import com.woniu.staff.cliententity.form.AddAccountForm;
import com.woniu.staff.cliententity.form.AddAccountRoleForm;
import com.woniu.staff.cliententity.model.Account;
import com.woniu.staff.cliententity.model.AccountRole;
import com.woniu.staff.dto.EmployeeDto;
import com.woniu.staff.form.AddEmployeeForm;
import com.woniu.staff.form.AddStationBossForm;
import com.woniu.staff.mapper.EmployeeMapper;
import com.woniu.staff.model.Employee;
import com.woniu.staff.param.*;
import com.woniu.staff.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.EOFException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
@Transactional
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Resource
    private StationClient stationClient;
    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired
    private PermissionsClient permissionsClient;

    /**
     * 新增员工
     * @param form 新增员工的form对象
     * @return 新增成功输出成功的员工对象失败为空抛异常
     * @throws Exception
     */
    @Override
    public Employee insert(AddEmployeeForm form) throws Exception {
        Result<Account> accountResult1 = permissionsClient.selectAccount(form.getPhone());
        if (accountResult1.getCode()!=200){
            throw new RebornException(accountResult1.getMessage(),accountResult1.getCode());
        }
        Account data = accountResult1.getData();
        Employee employee = BeanUtil.toBean(form, Employee.class);
        if (data!=null){
            //如果该员工存在账号 判断是否为删除状态 否则抛异常
            if (accountResult1.getData().getAccountState()!=1){
                throw new AccountException(AccountExceptionCode.ACCOUNT_ALREADY_EXISTS);
            }
            AddAccountForm addAccountForm = new AddAccountForm();
            addAccountForm.setAccountPass(form.getPassword());
            addAccountForm.setAccountPhone(form.getPhone());
            Result<Account> accountResult = permissionsClient.addAccount(addAccountForm);
            if (accountResult.getCode()!=200){
                throw new Exception(accountResult.getMessage());
            }

        }else{
            //如果该员工没有账号 则新增
            Result<Account> accountResult = permissionsClient.addAccount(new AddAccountForm("123456", form.getPhone()));
            if (accountResult.getCode()!=200){
                throw new RebornException(accountResult.getMessage(),accountResult.getCode());
            }
            Account data1 = accountResult.getData();
            employee.setAccountId(Long.valueOf(data1.getAccountId()));
            //再新增账号角色关联表
            AddAccountRoleDto addAccountRoleDto = new AddAccountRoleDto(Long.valueOf(data1.getAccountId()), 2L);
            Result<AddAccountRoleDto> roleDtoResult = permissionsClient.addAccountRole(addAccountRoleDto);
            if (roleDtoResult.getCode()!=200) {
                throw new RebornException(roleDtoResult.getMessage(),roleDtoResult.getCode());
            }
        }
        employee.setRoleId(2L);
        employee.setRoleName("员工");
        employee.setState(0L);
        employeeMapper.insert(employee);
        return employee;
    }

    /**
     * 根据站点id和状态查询相应的员工信息 无状态则查站点全部员工
     * @param form 站点id  和状态id
     * @return 输出查询到的员工对象集合
     */
    @Override
    public Page<Employee> findAllByStationId(FindAllStateEmployeeParam form) {
        if (form.getPageNum()==null){
            form.setPageNum(1);
        }
        if (form.getPageSize()==null){
            form.setPageSize(5);
        }
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",form.getStationId());
        if (form.getState()!=null){
            wrapper.eq("state",form.getState());
        }
        Page<Employee> employeePage = new Page<>(form.getPageNum(), form.getPageSize());
        employeeMapper.selectPage(employeePage, wrapper);
        return employeePage;
    }

    /**
     * 修改员工状态
     * @param toBean 员工id 状态码
     * @return 返回修改成功后的员工对象dto
     * @throws Exception
     */
    @Override

    public EmployeeDto UpdateEmployeeStateForm(UpdateEmployeeStateParam toBean) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",toBean.getAccountId());
        Employee employee = employeeMapper.selectOne(wrapper);
        if (employee==null){
            throw new AccountException(AccountExceptionCode.EMPLOYEE_NO_USER);
        }
        employee.setState(toBean.getState());
        employeeMapper.updateById(employee);
        EmployeeDto dto = BeanUtil.toBean(employee, EmployeeDto.class);
        return dto;
    }
    /**
     * 通过员工账号id修改员工载重量
     * @param param 员工账号id 载重量
     * @return 返回修改后的员工dto
     */
    @Override
    public EmployeeDto updateEmployeeLoad(UpdateEmployeeLoadParam param) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",param.getAccountId());
        Employee employee = employeeMapper.selectOne(wrapper);
        if (employee==null){
            throw new AccountException(AccountExceptionCode.EMPLOYEE_NO_USER);
        }
        employee.setWeight(param.getLoad());
        employeeMapper.updateById(employee);
        EmployeeDto dto = BeanUtil.toBean(employee, EmployeeDto.class);
        return dto;
    }

    /**
     * 员工登录
     * @param toBean 账号密码
     * @return 输出登录对象
     */
    @Override
    public EmployeeDto login(EmployeeLoginParam toBean) {
        Result<AccountDto> login = permissionsClient.login(BeanUtil.toBean(toBean, AccountLoginForm.class));
        if (login.getCode()!=200){
            throw new PermissionsException(login.getCode(),login.getMessage());
        }
        System.out.println(JSONUtil.toJsonStr(login));



        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",login.getData().getAccountId().longValue());
        Employee employee = employeeMapper.selectOne(wrapper);



        if (employee==null){
            throw new StaffException(StaffExceptionCode.STAFF_EXCEPTION_CODE_NO_ACCOUNT);
        }
        EmployeeDto employeeDto =BeanUtil.toBean(employee,EmployeeDto.class);
        employeeDto.setAccount_phone(login.getData().getAccountPhone());
        return employeeDto;
    }

    /**
     * 分页查询所有可用的管理员工
     * @param toBean 分页对象
     * @return 分页page对象
     */
    @Override
    public Page<EmployeeDto> findUsefulHandlerPage(PageParam toBean) {
        if(toBean.getPageNum()==null){
            toBean.setPageNum(1);
        }
        if (toBean.getPageSize()==null){
            toBean.setPageSize(3);
        }
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",2);
        wrapper.eq("state",0);
        Page<Employee> employeePage = new Page<>(toBean.getPageNum(), toBean.getPageSize());
        employeeMapper.selectPage(employeePage,wrapper);
        List<EmployeeDto> employeeDtos = BeanUtil.copyToList(employeePage.getRecords(), EmployeeDto.class);
        Page page = BeanUtil.toBean(employeePage, Page.class);
        page.setRecords(employeeDtos);
        return page;
    }


    /**
     * 查询所有可用的员工
     * @return
     */
    @Override
    public List<EmployeeDto> findUsefulHandler() {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",2);
        wrapper.eq("state",0);
        List<Employee> employees = employeeMapper.selectList(wrapper);
        List<EmployeeDto> employeeDtos = BeanUtil.copyToList(employees, EmployeeDto.class);
        return employeeDtos;
    }
    /**
     * 查询除自己外的其他可用管理员id
     * @param id 管理员id
     * @return 管理员对象集合
     */
    @Override
    public List<EmployeeDto> showUsefulHandlerExceptOne(Integer id) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",4);
        wrapper.eq("state",0);
        wrapper.ne("id",id);
        List<Employee> employees = employeeMapper.selectList(wrapper);
        List<EmployeeDto> employeeDtos = BeanUtil.copyToList(employees, EmployeeDto.class);
        return employeeDtos;
    }
    /**
     * 根据账号查询员工对象
     * @param accountId 账号id
     * @return 返回账号对象
     */
    @Override
    public EmployeeDto findEmployeeByAccountId(String accountId) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",accountId);
        Employee employee = employeeMapper.selectOne(wrapper);
        EmployeeDto employeeDto = BeanUtil.toBean(employee, EmployeeDto.class);
        return employeeDto;
    }

    /**
     * 判断一个站点是否有员工(负责人除外)
     * @param stationId 站点id
     * @return 有返回true 无false
     */
    @Override
    public Boolean isHaveEmploye(String stationId, String handlerId) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",stationId);
        wrapper.ne("account_id",handlerId);
        List<Employee> employees = employeeMapper.selectList(wrapper);
        if (employees.size()!=0){
            return true;
        }
        return false;
    }

    /**
     * 查询一个站点的所有员工(负责人除外)
     * @param handlerId 负责人id
     * @return handlerId 管理员账号id
     */
    @Override
    public Page<Employee> findAllByStationIdWithoutHandler(int handlerId,int pageNum,int pageSize) {
        Employee handler = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("account_id", handlerId));
        if (handler==null){
            throw new RebornException("站长id有误",10005);
        }
        Result<StationDto> result = stationClient.byId(Math.toIntExact(handler.getStationId()));
        if(result.getCode()!=200){
            throw new RebornException(result.getMessage(),result.getCode());
        }
        StationDto data = result.getData();
        if(data==null){
            throw new RebornException("不存在的站点",10004);
        }


        Page<Employee> employeePage = new Page<>(pageNum, pageSize);
        QueryWrapper<Employee> wrapper = new QueryWrapper<Employee>().eq("station_id", data.getId());


        Page<Employee> page = employeeMapper.selectPage(employeePage,wrapper);
        if (page.getRecords()!=null&&!page.getRecords().isEmpty()){
            page.getRecords().removeIf(o->o.getAccountId()==handlerId);
        }
        return page;
    }


    /**
     * 开除员工id
     * @param id 员工id
     */
    @Override
    public void del(Integer id) {
        //查询员工
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",id);
        Employee employee = employeeMapper.selectOne(wrapper);
        if (employee==null) {
            throw new RebornException("该员工不存在",50001);
        }
        //判断该员工是否有未完成的订单(如果不是禁用状态 则没有未完成的订单)
        if (employee.getState()!=2){
            throw new RebornException("只能删除状态为禁用的员工",50003);
        }
        if (employee.getState() ==1) {
            throw new RebornException("员工已被开除",50002);
        }

        employee.setState(1L);
        updateById(employee);

    }

    @Override
    public Employee byAccountId(Integer id) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<Employee>().eq("account_id", id);
        return  employeeMapper.selectOne(wrapper);
    }

    @Override
    public Employee byStationId(String stationId) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id",stationId);
        wrapper.eq("role_id",3);
        Employee employee = employeeMapper.selectOne(wrapper);
        return employee;
    }

    @Override
    public Employee byId(Integer id) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<Employee>().eq("account_id", id);
        return employeeMapper.selectOne(wrapper);
    }

    @Override
    public Employee addEmployeeUser(Integer userId, AddEmployeeUserParam toBean) {
        Result<Account> accountResult1 = permissionsClient.selectAccount(toBean.getPhone());
        if (accountResult1.getCode()!=200){
            throw new RebornException(accountResult1.getMessage(),accountResult1.getCode());
        }
        if (accountResult1!=null){
            //如果该员工存在账号 判断是否为删除状态 否则抛异常
            if (accountResult1.getData().getAccountState()!=1){
                throw new AccountException(AccountExceptionCode.ACCOUNT_ALREADY_EXISTS);
            }
        }
        AddAccountForm account = new AddAccountForm();
        account.setAccountPhone(toBean.getPhone());
        account.setAccountPass("123456");
        Result<Account> accountResult = permissionsClient.addAccount(account);
        if (accountResult.getCode()!=200){
            throw new PermissionsException(accountResult.getCode(),accountResult.getMessage());
        }
        AddAccountRoleForm addAccountRoleForm = new AddAccountRoleForm();
        addAccountRoleForm.setAccountId(accountResult.getData().getAccountId().longValue());
        addAccountRoleForm.setRoleId((long)2);
        Result<AccountRole> accountRoleResult = permissionsClient.addAccountRole(addAccountRoleForm);
        if (accountRoleResult.getCode()!=200){
            throw new PermissionsException(accountRoleResult.getCode(),accountRoleResult.getMessage());
        }
        Employee employee = new Employee();
        employee.setAccountId(accountResult.getData().getAccountId().longValue());
        employee.setEmployeName(toBean.getEmployeeName());
        employee.setState((long)0);
        employee.setPhone(toBean.getPhone());
        employee.setQq(toBean.getQq());
        employee.setRoleId((long)2);
        employee.setRoleName("员工");
        employeeMapper.insert(employee);

        return employee;
    }

    @Override
    public Employee addEmployeeStation(Integer userId, AddEmployeeUserParam toBean) {
        Result<Account> accountResult1 = permissionsClient.selectAccount(toBean.getPhone());
        if (accountResult1.getCode()!=200){
            throw new RebornException(accountResult1.getMessage(),accountResult1.getCode());
        }
        if (accountResult1!=null){
            //如果该员工存在账号 判断是否为删除状态 否则抛异常
            if (accountResult1.getData().getAccountState()!=1){
                throw new AccountException(AccountExceptionCode.ACCOUNT_ALREADY_EXISTS);
            }
        }

        AddAccountForm account = new AddAccountForm();
        account.setAccountPhone(toBean.getPhone());
        account.setAccountPass("123456");
        Result<Account> accountResult = permissionsClient.addAccount(account);
        if (accountResult.getCode()!=200){
            throw new PermissionsException(accountResult.getCode(),accountResult.getMessage());
        }
        AddAccountRoleForm addAccountRoleForm = new AddAccountRoleForm();
        addAccountRoleForm.setAccountId(accountResult.getData().getAccountId().longValue());
        addAccountRoleForm.setRoleId((long)3);
        Result<AccountRole> accountRoleResult = permissionsClient.addAccountRole(addAccountRoleForm);
        if (accountRoleResult.getCode()!=200){
            throw new PermissionsException(accountRoleResult.getCode(),accountRoleResult.getMessage());
        }
        Employee employee = new Employee();
        employee.setAccountId(accountResult.getData().getAccountId().longValue());
        employee.setEmployeName(toBean.getEmployeeName());
        employee.setState((long)0);
        employee.setPhone(toBean.getPhone());
        employee.setQq(toBean.getQq());
        employee.setRoleId((long)3);
        employee.setRoleName("站长");
        employeeMapper.insert(employee);

        return employee;
    }

    @Override
    public Employee addStationBoss(AddStationBossForm form) throws Exception {
        Result<Account> accountResult1 = permissionsClient.selectAccount(form.getPhone());
        if (accountResult1.getCode()!=200){
            throw new RebornException(accountResult1.getMessage(),accountResult1.getCode());
        }
        Account data = accountResult1.getData();
        Employee employee = BeanUtil.toBean(form, Employee.class);
        if (data!=null){
            //如果该员工存在账号 判断是否为删除状态 否则抛异常
            if (accountResult1.getData().getAccountState()!=1){
                throw new AccountException(AccountExceptionCode.ACCOUNT_ALREADY_EXISTS);
            }
            AddAccountForm addAccountForm = new AddAccountForm();
            addAccountForm.setAccountPass(form.getPassword());
            addAccountForm.setAccountPhone(form.getPhone());
            Result<Account> accountResult = permissionsClient.addAccount(addAccountForm);
            if (accountResult.getCode()!=200){
                throw new Exception(accountResult.getMessage());
            }

        }else{
            //如果该员工没有账号 则新增
            Result<Account> accountResult = permissionsClient.addAccount(new AddAccountForm("123456", form.getPhone()));
            if (accountResult.getCode()!=200){
                throw new RebornException(accountResult.getMessage(),accountResult.getCode());
            }
            Account data1 = accountResult.getData();
            employee.setAccountId(Long.valueOf(data1.getAccountId()));
            //再新增账号角色关联表
            AddAccountRoleDto addAccountRoleDto = new AddAccountRoleDto(Long.valueOf(data1.getAccountId()), 3L);
            Result<AddAccountRoleDto> roleDtoResult = permissionsClient.addAccountRole(addAccountRoleDto);
            if (roleDtoResult.getCode()!=200) {
                throw new RebornException(roleDtoResult.getMessage(),roleDtoResult.getCode());
            }
        }
        employee.setRoleId(3L);
        employee.setRoleName("站长");
        employee.setState(0L);
        employeeMapper.insert(employee);
        return employee;
    }

    @Override
    public List<EmployeeDto> findUsefulHandlerExcept(Integer employId) {
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",2);
        wrapper.eq("state",0);
        wrapper.ne("account_id",employId);
        List<Employee> employees = employeeMapper.selectList(wrapper);
        List<EmployeeDto> employeeDtos = BeanUtil.copyToList(employees, EmployeeDto.class);
        return employeeDtos;
    }

    /**
     * 员工绑定站点
     * id 账号id roleId 角色id
     */
    @Override
    public Employee bindingStation(Integer id, Integer stationId) {
        Employee employee = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("account_id", id));
        if (employee==null){
            throw new RebornException("不存在的员工",80001);
        }
        employee.setStationId(Long.valueOf(stationId));
        employeeMapper.updateById(employee);
        return employee;
    }


}
